#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QFile>
#include <QCryptographicHash>
#include <QMessageBox>
#include <QDebug>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    this->setWindowFlag(Qt::WindowMaximizeButtonHint, false);

    bool is_file_exist = false;
    if (QFile::exists("data.db")) {
        is_file_exist = true;
    }

    this->db = QSqlDatabase::addDatabase("QSQLITE", "main");
    this->db.setDatabaseName("data.db");
    if (!this->db.open()) {
        QMessageBox::critical(this, "系统错误", "无法打开数据库");
        exit(1);
    }

    if (!is_file_exist) {
        this->db.exec("CREATE TABLE `class`("
                      "`id` INTEGER PRIMARY KEY AUTOINCREMENT,"
                      "`name` TEXT,"
                      "`group_name` VARCHAR(2)"
                      ")");
        this->err = this->db.lastError();
        if (this->err.isValid()) {
            QMessageBox::critical(this, "系统错误", "数据表创建失败：" + this->err.databaseText());
            this->db.close();
            QSqlDatabase::removeDatabase("main");
            exit(1);
        }
        this->db.exec("CREATE TABLE `item`("
                      "`id` INTEGER PRIMARY KEY AUTOINCREMENT,"
                      "`name` TEXT,"
                      "`init_score` INT(4)"
                      ")");
        this->err = this->db.lastError();
        if (this->err.isValid()) {
            QMessageBox::critical(this, "系统错误", "数据表创建失败：" + this->err.databaseText());
            this->db.close();
            QSqlDatabase::removeDatabase("main");
            exit(1);
        }
        this->db.exec("CREATE TABLE `score`("
                      "`id` INTEGER PRIMARY KEY AUTOINCREMENT,"
                      "`class_id` INTEGER,"
                      "`item_id` INTEGER,"
                      "`op_score` INT(4),"
                      "`date_time` INT(11)"
                      ")");
        this->err = this->db.lastError();
        if (this->err.isValid()) {
            QMessageBox::critical(this, "系统错误", "数据表创建失败：" + this->err.databaseText());
            this->db.close();
            QSqlDatabase::removeDatabase("main");
            exit(1);
        }
        this->db.exec("CREATE TABLE `user`("
                      "`id` INTEGER PRIMARY KEY AUTOINCREMENT,"
                      "`account` TEXT,"
                      "`password` TEXT"
                      ")");
        this->err = this->db.lastError();
        if (this->err.isValid()) {
            QMessageBox::critical(this, "系统错误", "数据表创建失败：" + this->err.databaseText());
            this->db.close();
            QSqlDatabase::removeDatabase("main");
            exit(1);
        }
    }
}

MainWindow::~MainWindow()
{
    if (this->db.isOpen()) {
        this->db.close();
    }
    QSqlDatabase::removeDatabase("main");
    delete ui;
}

QString MainWindow::md5(QString str) {
    QString ret;
    QByteArray ret_byte = QCryptographicHash::hash(str.toLatin1(), QCryptographicHash::Md5);
    ret.append(ret_byte.toHex());
    return ret;
}

void MainWindow::on_login_btn_clicked()
{
    this->db = QSqlDatabase::addDatabase("QSQLITE", "main");
    this->db.setDatabaseName("data.db");
    if (!this->db.open()) {
        QMessageBox::critical(this, "系统错误", "无法打开数据库");
        return;
    }
    QString account = this->ui->account_lineedit->text();
    QString password = this->ui->password_lineedit->text();
    if (account.length() == 0 || password.length() == 0) {
        QMessageBox::warning(this, "系统警告", "请输入账号密码");
        return;
    }
    if (account.contains('\\') || account.contains('"') || account.contains('\'') ||
            password.contains('\\') || password.contains('"') || password.contains('\'')) {
        QMessageBox::warning(this, "系统警告", "禁止输入\\、'或\"");
        return;
    }
    QString pwd = this->md5(password);
    QSqlQuery q(QString("SELECT COUNT(`id`) FROM `user` WHERE `account` = '") +
                account + QString("'"), this->db);
    if (q.next()) {
        if (q.value(0).toInt() == 0) {
            if (QMessageBox::information(this, "系统提示", "账号不存在，是否创建该账号？",
                                         QMessageBox::Yes, QMessageBox::No) ==
                    QMessageBox::Yes) {
                this->db.exec(QString("INSERT INTO `user`(`account`, `password`) VALUES(") +
                              QString("'") + account + QString("', '") + pwd + QString("')"));
                this->err = this->db.lastError();
                if (this->err.isValid()) {
                    QMessageBox::critical(this, "系统错误", "账号创建失败：" + this->err.databaseText());
                    return;
                } else {
                    if (QMessageBox::question(this, "操作成功", "账号创建成功，是否立即登录？",
                                              QMessageBox::Yes, QMessageBox::No) == QMessageBox::Yes) {
                        this->data_form = new DataForm();
                        this->data_form->show();
                        this->close();
                    }
                }
            }
        } else {
            QSqlQuery q2(QString("SELECT COUNT(`id`) FROM `user` WHERE `account` = '") + account +
                         QString("' AND `password` = '") + pwd + QString("'"), this->db);
            if (q2.next()) {
                if (q2.value(0).toInt() > 0) {
                    this->data_form = new DataForm();
                    this->data_form->show();
                    this->close();
                } else {
                    QMessageBox::critical(this, "系统错误", "账号或密码错误");
                    return;
                }
            } else {
                QMessageBox::warning(this, "系统警告", "找不到数据");
                return;
            }
        }
    } else {
        QMessageBox::warning(this, "系统警告", "找不到数据");
        return;
    }
}

